package cn.tpshion.vm.base.handle;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@ControllerAdvice
public class ResponseBodyHandle implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ServletServerHttpRequest tmpReq = (ServletServerHttpRequest) request;
        HttpServletRequest httpReq = tmpReq.getServletRequest();
        String respJson = JSON.toJSONString(body);
        String servletPath = httpReq.getServletPath();
        if(servletPath.contains("/actuator")){
            return body;
        }
        log.info("Response url:{} data:{}", servletPath, respJson);
        return body;
    }
}
